import os
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
import json

def load_config(file_path):
    """读取 JSON 配置文件并返回内容"""
    with open(file_path, 'r',encoding='utf-8') as file:
        config = json.load(file)
    return config


def collect_jpg_files(folder_paths):
    nested_list = []

    for folder in folder_paths:
        jpg_files = []
        folder_child = os.listdir(folder)
        # 遍历文件夹中的所有文件
        for child in folder_child:
            # 判断是否为文件 and 是否以小写的.jpg结尾
            if os.path.isfile(os.path.join(folder, child)) and child.lower().endswith('.jpg'):
                # 将完整路径添加到 jpg_files 列表
                jpg_files.append(os.path.join(folder, child))
        # 将每个文件夹的 jpg 文件列表添加到嵌套列表中
        nested_list.append(jpg_files)

    return nested_list

def run_krpanotools(input_file, krpanotools_path, config_path):
    command = [krpanotools_path, 'makepano', config_path ] + input_file
    process = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    process.wait()  # 等待进程完成
    return process.returncode


def make_vtour(folder_paths,config_file_path):
    print("MAKE VTOUR (VR-OPT) droplet")

    # 收集jpg文件
    nested_list = collect_jpg_files(folder_paths)

    # 加载配置
    config = load_config(config_file_path)
    # 访问配置内容
    max_workers = config.get('max_workers')
    krpanotools_path = config.get('krpanotools_path')
    config_path = config.get('config_path')

    # # 固定的 文件路径
    # krpanotools_path = r"E:\事务\上海\24上海家具展制作程序\1.文件生产\krpanotools.exe"  # 替换为实际的 krpanotools.exe 文件路径
    # config_path = r"E:\事务\上海\24上海家具展制作程序\1.文件生产\templates\vtour-vr.config"  # 替换为实际的配置文件路径
    # max_workers = 5 # 最大进程数量

    # 检查 krpanotools.exe 和配置文件是否存在
    if not os.path.exists(krpanotools_path):
        print(f"Error: The file '{krpanotools_path}' does not exist.")
        return

    if not os.path.exists(config_path):
        print(f"Error: The config file '{config_path}' does not exist.")
        return

    # r"E:\事务\上海\拍摄文件\原始数据\W11\W11A29\拼接图\vtour\data.xml"
    for folder_path in folder_paths:
        xml_path = os.path.join(folder_path,r'vtour\data.xml')
        if os.path.exists(xml_path):
            os.remove(xml_path)
            print(f"Removed {xml_path}")

    #     # 检查全景图像文件是否存在
    # for input_file in input_files:
    #     if not os.path.exists(input_file):
    #         print(f"Error: The file '{input_file}' does not exist.")
    #         return

    # 使用 ThreadPoolExecutor 管理进程
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = {executor.submit(run_krpanotools, input_file, krpanotools_path, config_path): input_file for
                   input_file in nested_list}

        for future in as_completed(futures):
            input_file = futures[future]
            try:
                return_code = future.result()
                if return_code == 0:
                    print(f"Success for vtour {input_file}")
                else:
                    print(f"Fail for vtour {input_file}")
            except Exception as e:
                print(f"Error occurred for {input_file}: {e}")

